package be.artesis.titamo.importer.cli;

import java.io.IOException;
import java.sql.SQLException;

import be.artesis.titamo.exceptions.DriverNotFoundException;
import be.artesis.titamo.exceptions.InterfaceNotFoundException;
import be.artesis.titamo.exceptions.InvalidEntryException;
import be.artesis.titamo.exceptions.TimeTableParserErrors;
import be.artesis.titamo.exceptions.ToleranceReachedException;
import be.artesis.titamo.importer.ImporterInterface;



public class CLInterface extends ImporterInterface {

	private static final int OPT_HELP = 1;
	private static final int OK = 0;
	private static final int FAILED = -1;
	
	private String tolerance_arg;
	
	private String[] args;
	
	public CLInterface(String[] args)
	{
		super();
		this.args = args;
	}
	
	private int parseArguments()
	{
		int success = OK;
		for (String a : args)
		{
			String[] opt = a.split("=");
			//System.out.println(opt[0]);
			//System.out.println(opt[1]);
			if (opt[0].equals("-file"))
			{
				super.filepath = opt[1].trim();
			}
			else if (opt[0].equals("-delimiter"))
			{
				super.delimiter = opt[1].trim();
			}
			else if (opt[0].equals("-subdelimiter"))
			{
				super.subdelimiter = opt[1].trim();
			}
			else if (opt[0].equals("-help"))
				return OPT_HELP;
			else if (opt[0].equals("-clear"))
			{
				super.clearDB = (!opt[1].equals("no"));
			}
			else if (opt[0].equals("-serverurl"))
			{
				super.connectionString = opt[1].trim();
			}
			else if (opt[0].equals("-username"))
			{
				super.username = opt[1].trim();
			}
			else if (opt[0].equals("-password"))
			{
				this.password = opt[1].trim();
			}
			else if (opt[0].equals("-tolerance"))
			{
				this.tolerance_arg = opt[1].trim();
			}
			else if (opt[0].equals("-force"))
			{
				super.forceImport = (!opt[1].equals("no"));
			}
			else
			{
				success = FAILED;
				System.err.println("invalid option: '" + opt[0] + "'\n\t for help of the usage of ttimport type 'ttimport -help'");
			}
		}
		return success;
	}

	private boolean checkArguments()
	{
		boolean success = true;
		if (filepath == null) 
		{
			System.err.println("a file-option must be set in order to import");
			success = false;
		}
		if (tolerance_arg != null)
		{
			try
			{
				super.errorTolerance = Integer.parseInt(tolerance_arg);
			}
			catch (NumberFormatException e)
			{
				System.err.println("The tolerance value can only contain numbers.");
				success = false;
			}
		}
		return success;
	}
	
	private void printHelpInformation() 
	{
		System.out.println(
				"ttimport HELP information\n" +
				"=========================\n" +
				"Usage of ttimport: \n" +
				"\t" + "ttimport -file=*filepath* [options]\n" +
				"The '-file' option is always required in order to import and specifies the raw timetable information file.\n" +
				"Available options are:\n" +
				"\t" + "-delimiter=*sequence*" + "\t\t" + "Sets the delimiter of the raw timetable information file. Change *sequence* to the character sequence you want to use for delimiting.\n" +
				"\t" + "-subdelimiter=*sequence*" + "\t" + "Sets the subdelimiter of the raw timetable information file. Change *sequence* to the character sequence you want to use for subdelimiting.\n" +
				"\t" + "-clear=[yes | no]" + "\t\t" + "Sets whether the timetable should be cleared or not.\n" +
				"\t" + "-forceimport=[yes | no]" + "\t\t" + "Sets whether the data should be imported despite parser errors.\n" +
				"\t" + "-tolerance=*number*" + "\t\t" + "Sets the error tolerance of parser errors. When the number is reached the program will never continue.\n" +
				"\t" + "-serverurl=*url*" + "\t\t" + "Sets the connection string to connect to the database.\n" +
				"\nWhen neither of these options are set the default settings will be used. You can change these options with the Graphical User Interface. To run this interface just run this program without any command-line arguments.\nPlease keep in mind that the -file option must be set at any time!"
		
		);
	}

	@Override
	protected void handleDriverNotFoundException(DriverNotFoundException e) {
		e.printStackTrace();
		
	}

	@Override
	protected void handleIOException(IOException e) {
		e.printStackTrace();
		
	}

	@Override
	protected void handleSQLException(SQLException e) {
		e.printStackTrace();
		
	}

	@Override
	protected void handleTableParserErrors(TimeTableParserErrors e) {
		System.out.print("");
		System.err.print("");
		System.err.println(e.getMessage());
		for (InvalidEntryException error : e.getList())
		{
			System.err.println("\tAt line " + error.getID() + ": " + error.getMessage());
		}
	}

	@Override
	protected void handleToleranceReachedException(ToleranceReachedException e) {
		e.printStackTrace();
		
	}
	
	@Override
	protected void handleInterfaceNotFoundException(InterfaceNotFoundException e) {
		e.printStackTrace();
		
	}

	@Override
	protected void printProgressInfo(String message) {
		System.out.println(message);
		
	}

	@Override
	protected void progressUpdate(int percent) {
		if (percent%10 == 1) System.out.print("=");
		if (percent == 100) System.out.println(" \tdone!");
	}

	@Override
	protected void postRun() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected boolean preRun() {
		
		int ret = parseArguments();
		
		if (ret == OPT_HELP)
		{
			printHelpInformation();
			return false;
		}
		else if (ret == FAILED)
			return false;
		if (!checkArguments()) return false;
		
		return true;
	}
}
